package com.kimwu.kill.mall.item.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kimwu.kill.mall.item.common.dto.StockGetItemDTO;
import com.kimwu.kill.mall.item.common.vo.ItemVO;
import com.kimwu.kill.mall.item.web.entity.Item;
import com.kimwu.kill.mall.item.web.entity.ItemStock;
import com.kimwu.kill.mall.item.web.service.IItemService;
import com.kimwu.kill.mall.item.web.service.IItemStockService;
import com.kimwu.kill.mall.redis.lock.annotation.RedisLock;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author KimWu
 * @since 2021-08-27
 */
@RestController
@RequestMapping("/item")
@Slf4j
public class ItemController {

    @Resource
    private IItemService itemService;
    @Resource
    private IItemStockService iItemStockService;

    @PostMapping("/v1/stockGetItem")
    @GlobalTransactional(rollbackFor = Exception.class)
    @RedisLock(name = "stockGetItem", value = "stockGetItem", expireTime = 10)
    public String stockGetItem(@RequestBody StockGetItemDTO dto) {
        log.info("准备扣减库存 ， 预下单数量 {}", dto.getAmount());
        ItemStock item_id = iItemStockService.getOne(new QueryWrapper<ItemStock>().eq("item_id", dto.getItemId()));
        if (item_id.getStock() > 0 && item_id.getStock() >= dto.getAmount()) {
            item_id.setStock(item_id.getStock() - dto.getAmount());
            iItemStockService.updateById(item_id);
            Item byId = itemService.getById(dto.getItemId());
            byId.setSales(byId.getSales() + dto.getAmount());
            itemService.updateById(byId);
            log.info("【成功】扣减库存 ， 下单数量 {} , 库存 {}", dto.getAmount(), item_id.getStock());
            return byId.getPrice().toString();
        } else {
            return "失败";
        }
    }

    @PostMapping("/v1/getAll")
    public List<ItemVO> getAll() {
        List<Item> itemList = itemService.list();
        List<ItemStock> itemStockList = iItemStockService.list();
        List<ItemVO> resultList = itemList.stream().map(i -> {
            ItemStock itemStock = itemStockList.stream().filter(is -> is.getItemId().equals(i.getId())).findFirst().get();
            return new ItemVO(
                    i.getId(), i.getPrice(), i.getSales(), itemStock.getStock()
            );
        }).collect(Collectors.toList());
        return resultList;

    }

}
